define(function (require) {
    var $ = require("jquery");
    require("pagination");
    require('angular-ui');
    require('angular-interceptor');
    require('global');

    var util = require("util");
    var ui = require("ui");
    var angular = require("angular");
    var _ = require('underscore');
    require('placeholder');

    angular.module('memberManage', [
        'ngInterceptor',
        'ngPublicUI',
        'ngPlaceholder'
    ])
        .constant('limit', 10)
        .constant('erplimit', 10)
        .constant('apibe', '/api/')
        .constant('NEED_TOKEN', 'true')
        .constant('apife', 'index.php?r=salesuser/sales-user/')
        .factory('url', [
            function () {
                return {
                    //给url添加search字符串
                    addParam: function (url, search) {
                        for (var key in search) {
                            if (search.hasOwnProperty(key) && search[key]) {
                                var connecter = "&";
                                if (url.indexOf('?') === -1) {
                                    connecter = "?";
                                }
                                url += connecter + key + '=' + encodeURIComponent(search[key]);
                            }
                        }
                        return url;
                    }
                };
            }
        ])
        .factory('http', [
            '$http',
            'url',
            'apibe',
            'apife',
            'NEED_TOKEN',
            function ($http, url, apibe, apife, NEED_TOKEN) {
                var requrl = apibe + apife;
                return {
                    get: function (api, search) {
                        search = angular.extend(search || {}, { rnd: Math.random() })
                        api = url.addParam(requrl + api, search);
                        return $http.get(api, { needToken: NEED_TOKEN });
                    },
                    post: function (api, data, search) {
                        var dataMap = [];
                        for (var key in data) {
                            if (data.hasOwnProperty(key)) {
                                var val = data[key];
                                if (angular.isObject(val)) {
                                    val = JSON.stringify(val);
                                }
                                dataMap.push(key + '=' + encodeURIComponent(val));
                            }
                        }
                        data = dataMap.join('&');
                        search = angular.extend(search || {}, { rnd: Math.random() })
                        api = url.addParam(requrl + api, search);
                        return $http.post(api, data, {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            needToken: NEED_TOKEN
                        });
                    }
                };
            }
        ])
        .factory('memberService', [
            'http',
            function (http) {
                var httpClient = {
                    get: function (api, options) {
                        return http.get(api, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    },
                    post: function (api, options) {
                        return http.post(api, options.data, options.search)
                            .success(function (res) {
                                if (res.retCode == 0) {
                                    return options.success(res);
                                }
                                options.fail && options.fail(res);
                            })
                            .error(function (res) {
                                options.fail && options.fail(res);
                            });
                    }
                };
                // 当所属项目的文字超过两行时,加上"..."
                // function checkMenberList(){
                //     setTimeout(function(){
                //         $.each($(".belong-project-text"),function(i,item){
                //             if($(this).height()>36){
                //                 $(this).parent().addClass("show-dotted")
                //             }
                //         })
                //     },500);
                // }
                return {
                    getMemberList: function (options) {
                        //checkMenberList();
                        return httpClient.get('list', options);
                    },
                    getErpUserList: function (options) {
                        return httpClient.get('get-erp-users', options);
                    },
                    deleteMember: function (options) {
                        return httpClient.post('delete', options);
                    },
                    enableMember: function (options) {
                        return httpClient.post('enable', options);
                    },
                    disableMember: function (options) {
                        return httpClient.get('disable', options);
                    },
                    leaveMember: function (options) {
                        return httpClient.post('disable', options);
                    },
                    holidayMember: function (options) {
                        return httpClient.post('on-holiday', options);
                    },
                    cleanHolidayMember: function(options){
                        return httpClient.post('on-duty', options);
                    },
                    importErpUser: function (options) {
                        return httpClient.post('import-erp-users', options);
                    },
                    createMember: function (options) {
                        return httpClient.post('save', options);
                    },
                    updateMember: function (options) {
                        return httpClient.post('save', options);
                    },
                    bindErpUser: function (options) {
                        return httpClient.post('bind', options);
                    },
                    unbindErpUser: function (options) {
                        return httpClient.post('unbind', options);
                    },
                    resetMemberPassword: function (options) {
                        return httpClient.post('reset-password', options);
                    },
                    genErp: function (options) {
                        return httpClient.get('generate-erp-user', options);
                    }
                };
            }
        ])
        .controller('MemberController', [
            '$scope',
            '$rootScope',
            '$compile',
            'memberService',
            'limit',
            'erplimit',
            function ($scope, $rootScope, $compile, service, limit, erplimit) {

                //成员管理页面绑定ERP用户的弹窗组件
                $scope.erpUserBinder = {
                    init: function ($dialogScope, $dialog, userId) {
                        $scope.erpUserBinderDialog = $dialog;
                        $scope.erpUserBinder.userId = userId;
                        $scope.erpUserBinder.userList = null;
                        $scope.erpUserBinder.userListPager.total = 0;

                        $dialogScope.erpUserBinder = $scope.erpUserBinder;
                        $scope.getErpUserList(1, '', $scope.erpUserBinder.httpSuccess);
                    },
                    searchUsers: _.debounce(function () {
                        $scope.getErpUserList(1, $scope.erpUserBinder.keyword, $scope.erpUserBinder.httpSuccess);
                    },200),
                    //绑定和引入erp用户数据源是一样的，callback要传入
                    httpSuccess: function (res) {
                        $scope.erpUserBinder.userList = res.data.data;
                        $scope.erpUserBinder.userListPager.total = res.data.total;
                    },
                    select: function (index) {
                        $scope.erpUserBinder.selected = index;
                    },
                    submit: function ($dialog) {
                        //todo
                        var selected = $scope.erpUserBinder.userList[$scope.erpUserBinder.selected];
                        if (!selected) {
                            $rootScope.$emit('httpRequestError', '请选择用户');
                            return false;
                        }
                        return $scope.bindErp($scope.erpUserBinder.userId, selected.UserCode,$dialog);
                    },
                    genErpUser: function () {
                        $scope.genErpUser($scope.erpUserBinder.userId);
                        $scope.erpUserBinderDialog.close();
                    },
                    userListPager: {
                        pageSize: erplimit,
                        change: function (pageIndex,pageSize) {
                            $scope.getErpUserList(pageIndex, $scope.erpUserBinder.keyword, $scope.erpUserBinder.httpSuccess,pageSize);
                        }
                    }
                };

                //成员管理页面列表的分页组件
                $scope.memberListPager = {
                    pageSize: limit,
                    change: function (pageIndex, pageSize) {
                        $scope.getMemberList(pageIndex, pageSize);
                        $scope.memberListPager.pageSize = pageSize;
                        $scope.memberListPager.pageIndex = pageIndex;
                    }
                };

                //新增/编辑用户的弹窗组件
                $scope.memberManager = {
                    init: function ($dialogScope, userInfo) {
                        $dialogScope.memberManager = $scope.memberManager;
                        if (userInfo) {
                            $scope.memberManager.user = angular.copy(userInfo);
                        } else {
                            $scope.memberManager.user = {user_name:"",mobile_tel:""};
                        }
                    },
                    validate: function () {
                    },
                    create: function () {
                        var user = $scope.memberManager.user;
                        if (!user || !user.user_name) {
                            $rootScope.$emit('httpRequestError', '请填写用户姓名');
                            return false;
                        }
                        if (!user || !/^1\d{10}$/.test(user.mobile_tel)) {
                            $rootScope.$emit('httpRequestError', '手机号必须为1开头的11位有效数字');
                            return false;
                        }
                        $scope.createMember(user.user_name, user.mobile_tel);
                    },
                    update: function () {
                        var user = $scope.memberManager.user;
                        $scope.updateMember(user.s_userId, user.user_name, user.mobile_tel);
                    }
                };

                //重置密码组件
                $scope.passwordReseter = {
                    init: function ($dialogScope, userId) {
                        $scope.passwordReseter.userId = userId;
                        $scope.passwordReseter.pwd = '';// 初始化
                        $dialogScope.passwordReseter = $scope.passwordReseter;
                    },
                    validate: function () {

                    },
                    submit: function () {
                        return $scope.resetPassword($scope.passwordReseter.userId, $scope.passwordReseter.pwd);
                    }
                };

                //引入ERP用户组件
                $scope.erpUserImporter = {
                    init: function ($dialogScope) {
                        $scope.erpUserImporter.userList = [];
                        $scope.erpUserImporter.selectUserList = [];
                        $scope.erpUserImporter.userListPager.total = 0;
                        $dialogScope.erpUserImporter = $scope.erpUserImporter;
                        $scope.getErpUserList(1, '', $scope.erpUserImporter.httpSuccess);
                    },
                    searchUsers: _.debounce(function () {
                        $scope.getErpUserList(1, $scope.erpUserImporter.keyword, $scope.erpUserImporter.httpSuccess);
                    },200),
                    //绑定和引入erp用户数据源是一样的，callback要传入
                    httpSuccess: function (res) {
                        $scope.erpUserImporter.userList = res.data.data;
                        $scope.erpUserImporter.userListPager.total = res.data.total;
                        $scope.erpUserImporter.bindChecked();
                    },
                    selectUserList: [],
                    bindChecked : function(){
                        $scope.erpUserImporter.checker.all = false;
                        var list = $scope.erpUserImporter.userList || [];
                        _.each(list,function(item){
                            if(_.findIndex($scope.erpUserImporter.selectUserList, {UserGUID:item.UserGUID}) !== -1){
                                item.checked = true;
                            }
                        });
                    },
                    //erp列表checkbox选择
                    checker: {
                        selectItem: function (index) {
                            var item = $scope.erpUserImporter.userList[index];
                            var checkedIndex = _.findIndex($scope.erpUserImporter.selectUserList, {UserGUID:item.UserGUID});
                            if (item.checked) {
                                checkedIndex === -1 && $scope.erpUserImporter.selectUserList.push(angular.copy(item));
                            }else if(!item.checked){

                                //如果全选按钮选中，则取消选中
                                $scope.erpUserImporter.checker.all && ($scope.erpUserImporter.checker.all = false);
                                checkedIndex !== -1 && $scope.erpUserImporter.selectUserList.splice(checkedIndex,1);
                            }
                        },
                        selectAll: function () {
                            var all = $scope.erpUserImporter.checker.all;
                            if(all){
                                _.each($scope.erpUserImporter.userList,function(item,index){
                                    item.checked = true;
                                    $scope.erpUserImporter.checker.selectItem(index);
                                });
                            }else{
                                _.each($scope.erpUserImporter.userList,function(item,index){
                                    item.checked = false;
                                    $scope.erpUserImporter.checker.selectItem(index);
                                });
                            }
                        }
                    },
                    //erp列表checkbox选择
                    userChecker: {
                        selectItem: function (index) {
                            var item = $scope.erpUserImporter.selectUserList[index];
                            if (!item.checked) {
                                $scope.erpUserImporter.userChecker.all = false;
                            }
                        },
                        selectAll: function () {
                            var list = $scope.erpUserImporter.selectUserList;
                            var all = true;
                            for (var i = 0; i < list.length; i++) {
                                var item = list[i];
                                if (!item.checked) {
                                    all = false;
                                    break;
                                }
                            }
                            for (var i = 0; i < list.length; i++) {
                                var item = list[i];
                                item.checked = !all;
                            }
                            $scope.erpUserImporter.userChecker.all = !all;
                        }
                    },
                    addItem: function () {
                        var list = $scope.erpUserImporter.userList;
                        var chooseItem = false;
                        for (var i = 0; i < list.length; i++) {
                            var item = list[i];
                            if (item.checked) {
                                item.checked = false;
                                list.splice(i, 1);
                                i--;
                                var selected = false;
                                for (var j = 0; j < $scope.erpUserImporter.selectUserList.length; j++) {
                                    if ($scope.erpUserImporter.selectUserList[j].UserGUID === item.UserGUID) {
                                        selected = true;
                                        break;
                                    }
                                }
                                !selected && $scope.erpUserImporter.selectUserList.push(item);
                                chooseItem = true;
                            }
                        }
                        if (!chooseItem) {
                            $rootScope.$emit('httpRequestError',"请选择操作的行");
                        }
                        $scope.erpUserImporter.checker.all = false;
                    },
                    removeItem: function (index,item) {
                        var checkedItem = _.find($scope.erpUserImporter.userList, {UserGUID:item.UserGUID});
                        if(checkedItem){
                            checkedItem.checked = false;
                            $scope.erpUserImporter.checker.all = false;
                        }
                        $scope.erpUserImporter.selectUserList.splice(index,1);
                    },
                    userListPager: {
                        pageSize: erplimit,
                        change: function (pageIndex,pageSize) {
                            $scope.getErpUserList(pageIndex, $scope.erpUserImporter.keyword, $scope.erpUserImporter.httpSuccess,pageSize);
                        }
                    },
                    submit: function ($dialog) {
                        return $scope.importErpUser($scope.erpUserImporter.selectUserList,$dialog);
                    }
                };

                /*
                 * 按条件搜索成员列表
                 */
                $scope.searchMembers = function () {
                    $scope.getMemberList(1);
                };

                /*
                 * 获取成员列表
                 */
                $scope.getMemberList = function (page, size) {
                    var search = {
                        page_index: page || 1,
                        page_size: size || $scope.memberListPager.pageSize || limit,
                        keyword: $scope.keyword,
                        status: $scope.search_field,
                        bind_status: $scope.search_erp_field
                    };
                    service.getMemberList({
                        search: search,
                        success: function (res) {
                            $scope.memberList = res.data.data;
                            $scope.memberListPager.total = res.data.total;
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '获取成员列表失败');
                        }
                    });
                };

                /*
                 * 获取erp用户列表
                 */
                $scope.getErpUserList = function (page, keyword, cb,pageSize) {
                    service.getErpUserList({
                        search: {
                            page_index: page,
                            page_size: pageSize || erplimit,
                            keyword: keyword
                        },
                        success: function (res) {
                            cb && cb(res);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '获取ERP用户列表失败');
                        }
                    })
                };

                /*
                 * 删除成员
                 */
                $scope.deleteMember = function (userId) {
                    service.deleteMember({
                        data: {
                            s_userId: userId
                        },
                        success: function (res) {
                            $scope.getMemberLastPageList();
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '删除成员失败');
                        }
                    })
                };

                // 剩下最后一行时，刷新上一页
                $scope.getMemberLastPageList = function () {
                    if($scope.memberList.length === 1 && $scope.memberListPager.pageIndex > 1){
                        $scope.memberListPager.pageIndex--;
                    }
                    $scope.getMemberList($scope.memberListPager.pageIndex);
                };

                $scope.leaveMember = function (userId) {
                    util.confirm('<p style="text-align: center">确定要置为离职吗？</p>' +
                                '<p style="text-indent: 2em">一旦置为离职，当前成员将从所在的销售团队中移出，已发生的业务数据会保留，不再参与后续各类业务。</p>',
                                {
                                    title: '置为离职',
                                    width: '500',
                                    ok: function () {
                                        service.leaveMember({
                                            data: {
                                                s_userId: userId
                                            },
                                            success: function (res) {
                                                util.notify('置为离职成功');
                                                $scope.getMemberLastPageList();
                                            },
                                            fail: function (res) {
                                                //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                                            }
                                        });
                                    }
                                });
                };
                $scope.enableMember = function (userId) {
                    util.confirm('<p style="text-align: center">确定要置为在职吗？</p>' +
                        '<p style="text-indent: 2em">置为在职后，需要重新加入项目团队，进而设置参加轮询等。</p>',
                        {
                            title: '置为在职',
                            width: '430',
                            ok: function () {
                                service.enableMember({
                                    data: {
                                        s_userId: userId
                                    },
                                    success: function (res) {
                                        util.notify('置为在职成功');
                                        $scope.getMemberLastPageList();
                                    },
                                    fail: function (res) {
                                        //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                                    }
                                });
                            }
                        });
                };
                $scope.holidayMember = function (userId) {
                    util.confirm('<p style="text-align: center">确定要标识当前成员为休假状态吗？</p>' +
                        '<p style="text-align: center">一旦标识为休假，当前成员将不再参与日常的自动分配客户。</p>',
                        {
                            title: '标识休假',
                            width: '500',
                            ok: function () {
                                service.holidayMember({
                                    data: {
                                        s_userId: userId
                                    },
                                    success: function (res) {
                                        util.notify('标识休假成功');
                                        $scope.getMemberLastPageList();
                                    },
                                    fail: function (res) {
                                        //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                                    }
                                });
                            }
                        });
                };
                $scope.cleanHolidayMember = function (userId) {
                    util.confirm('<p style="text-align: center">确定该成员已结束休假吗？</p>' +
                        '<p style="text-align: center">一旦结束休假，当前成员将恢复在职状态，参与日常的自动分配客户。</p>',
                        {
                            title: '结束休假',
                            width: '500',
                            ok: function () {
                                service.cleanHolidayMember({
                                    data: {
                                        s_userId: userId
                                    },
                                    success: function (res) {
                                        util.notify('结束休假成功');
                                        $scope.getMemberLastPageList();
                                    },
                                    fail: function (res) {
                                        //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                                    }
                                });
                            }
                        });
                };

                /*
                 * 禁用成员
                 */
                $scope.disableMember = function (userId) {
                    service.disableMember({
                        search: {
                            s_userId: userId
                        },
                        success: function (res) {
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                        }
                    })
                };

                /*
                 * 引入erp用户
                 */
                $scope.importErpUser = function (userList,$dialog) {
                    var users = [];
                    for (var i = 0; i < userList.length; i++) {
                        var user = userList[i];
                        if (user.MobilePhone === "") {
                            $rootScope.$emit('httpRequestError',"请填写手机号");
                            return false;
                        }
                        if (!/^1\d{10}$/.test(user.MobilePhone)) {
                            $rootScope.$emit('httpRequestError',"手机号必须为1开头的11位有效数字");
                            return false;
                        }
                        users.push({
                            "user_code": user.UserCode,
                            "user_name": user.UserName,
                            "mobile_tel": user.MobilePhone
                        });
                    }
                    if (!users.length) {
                        $rootScope.$emit('httpRequestError',"请选择成员");
                        return false;
                    }
                    service.importErpUser({
                        data: {
                            users: users
                        },
                        success: function (res) {
                            $dialog.close();
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '操作失败');
                        }
                    });
                    return false;
                };

                /*
                 * 新建成员
                 */
                $scope.createMember = function (name, mobile) {
                    service.createMember({
                        data: {
                            user_name: name,
                            mobile_tel: mobile
                        },
                        success: function (res) {
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '添加用户失败');
                        }
                    })
                };

                /*
                 * 更新成员信息
                 */
                $scope.updateMember = function (userId, name, mobile) {
                    service.updateMember({
                        data: {
                            s_userId: userId,
                            user_name: name,
                            mobile_tel: mobile
                        },
                        success: function (res) {
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '编辑成员失败');
                        }
                    })
                };

                /*
                 * 绑定
                 */
                $scope.bindErp = function (userId, name,dialog) {
                    service.bindErpUser({
                        data: {
                            s_userId: userId,
                            erp_user_code: name
                        },
                        success: function (res) {
                            //$rootScope.$emit('httpRequestSuccess', '绑定成功');
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                            dialog.close();
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '绑定失败');
                        }
                    });
                    return false;
                };

                /*
                 * 解绑
                 */
                $scope.unbindErp = function (userId) {
                    service.unbindErpUser({
                        data: {
                            s_userId: userId
                        },
                        success: function (res) {
                            //$rootScope.$emit('httpRequestSuccess', '解绑成功');
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '解绑失败');
                        }
                    });
                };

                /*
                 * 重置密码
                 */
                $scope.resetPassword = function (userId, pwd) {
                    if (!pwd) {
                        $rootScope.$emit('httpRequestError',"密码不能为空");
                        return false;
                    }
                    service.resetMemberPassword({
                        data: {
                            s_userId: userId,
                            new_password: pwd
                        },
                        success: function (res) {
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '重置密码失败');
                        }
                    });
                };
            
                /*
                 * 生成ERP用户
                 */
                $scope.genErpUser = function (userId) {
                    service.genErp({
                        search: {
                            s_userId: userId
                        },
                        success: function (res) {
                            $scope.getMemberList($scope.memberListPager.pageIndex);
                        },
                        fail: function (res) {
                            //$rootScope.$emit('httpRequestFail', res.errMsg || '生成ERP用户失败');                          
                        }
                    });
                };
            
                //下拉选项
                
                $scope.searchFields = [
                    {
                        name: '在职',
                        value: '0'
                    },
                    {
                        name: '离职',
                        value: '1'
                    },
                    {
                        name: '休假',
                        value: '2'
                    },
                    {
                        name: '全部',
                        value: '3'
                    }
                ];
                
                $scope.search_field = $scope.searchFields[0].value;

                $scope.searchErpFields = [
                    {
                        name: '全部',
                        value: '2'
                    },
                    {
                        name: '是',
                        value: '1'
                    },
                    {
                        name: '否',
                        value: '0'
                    }
                ];

                $scope.search_erp_field = $scope.searchErpFields[0].value;
            
            
                $scope.$watch('search_field',function(cur,old){
                    if (cur !== old) {
                        $scope.searchMembers();
                    }
                });

                $scope.$watch('search_erp_field',function(cur,old){
                    if (cur !== old) {
                        $scope.searchMembers();
                    }
                });
                //初始化后就要获取成员列表显示数据
                $scope.getMemberList(1);
            }
        ])

    angular.element(document).ready(function () {
        angular.bootstrap(document, ['memberManage']);
    });
});
